package com.om.abom.ws;

import com.alibaba.fastjson2.JSON;
import com.om.abom.service.UpgradeRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Component
@Slf4j
public class WsHandlerManageServer extends TextWebSocketHandler
{
    @Autowired
    UpgradeRecordService upgradeRecordService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session)
    {
        log.info("wsHandlerManageServer 连接已建立");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException, InterruptedException
    {
        // 处理接收到的文本消息
        String receivedMessage = message.getPayload();
        log.debug("接收到的消息：{}", receivedMessage);

        SocketReceiveData socketReceiveData = JSON.parseObject(receivedMessage, SocketReceiveData.class);
        log.info("接收到的消息：{}", socketReceiveData);

        if ("upgrade".equals(socketReceiveData.action)) {
            upgradeRecordService.upgrade(socketReceiveData.data, session);
        } else if ("restore".equals(socketReceiveData.action)) {
            upgradeRecordService.restore(socketReceiveData.data, session);
        }
    }

    public record SocketReceiveData(String action, long data)
    {
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
    {
        log.info("wsHandlerManageServer 连接已关闭");
    }
}
